package com.artron.mediaartron.ui.fragment.made;

import android.animation.AnimatorSet;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.BottomSheetDialog;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.artron.baselib.base.BaseStaticFragment;
import com.artron.baselib.entity.Response;
import com.artron.baselib.utils.ToastUtil;
import com.artron.baselib.utils.UIUtils;
import com.artron.mediaartron.R;
import com.artron.mediaartron.data.config.AppProfile;
import com.artron.mediaartron.data.entity.FrameData;
import com.artron.mediaartron.data.entity.ImageData;
import com.artron.mediaartron.data.entity.SameSizeFrame;
import com.artron.mediaartron.data.entity.UploadMaterialData;
import com.artron.mediaartron.data.entity.User;
import com.artron.mediaartron.data.entity.Works;
import com.artron.mediaartron.data.net.NetConstant;
import com.artron.mediaartron.data.net.RetrofitHelper;
import com.artron.mediaartron.data.production.CreateFrameData;
import com.artron.mediaartron.data.production.SuitableSizeHelper;
import com.artron.mediaartron.data.task.AddShoppingCartTask;
import com.artron.mediaartron.data.task.MaterialLibraryTask;
import com.artron.mediaartron.ui.activity.CustomSelectionActivity.Type;
import com.artron.mediaartron.ui.activity.GeneralActivity;
import com.artron.mediaartron.ui.activity.PreviewActivity;
import com.artron.mediaartron.ui.adapter.SelectionVerticalPagerAdapter;
import com.artron.mediaartron.ui.fragment.dialog.ProgressDialogFragment;
import com.artron.mediaartron.ui.fragment.factory.CustomSelectionVerticalFragmentFactory;
import com.artron.mediaartron.ui.fragment.factory.HomeFragmentFactory;
import com.artron.mediaartron.ui.helper.ThrottleFirstClickHelper;
import com.artron.mediaartron.ui.widget.CustomHorizontalViewPager;

import java.util.List;

import butterknife.BindView;
import rx.Observable;
import rx.functions.Action0;
import rx.functions.Action1;

import static com.artron.mediaartron.ui.activity.CustomSelectionActivity.CUSTOM_MADE;
import static com.artron.mediaartron.ui.activity.CustomSelectionActivity.POSTER;
import static com.artron.mediaartron.ui.helper.ThrottleFirstClickHelper.throttleFirst;

/**
 * Class description here
 *
 * @author doing
 * @version 1.0.0
 * @since 2017-09-21.
 */

public class CustomSelectionFragment extends BaseStaticFragment implements View.OnClickListener {

    private static final String TAG = "CustomSelectionFragment";

    @BindView(R.id.CustomSelectionFragment_ll_container)
    protected LinearLayout mLlContainer;
    @BindView(R.id.CustomSelectionFragment_et_name)
    protected EditText mEtName;
    @BindView(R.id.CustomSelectionFragment_v_pager)
    protected CustomHorizontalViewPager mViewPager;
    @BindView(R.id.CustomSelectionFragment_tv_price)
    protected TextView mTvPrice;
    @BindView(R.id.CustomSelectionFragment_tv_content)
    protected TextView mTvContent;
    @BindView(R.id.CustomSelectionFragment_tv_size)
    protected TextView mTvSize;
    @BindView(R.id.CustomSelectionFragment_btn_next)
    protected Button mBtnNext;
    @BindView(R.id.CustomSelectionFragment_tv_tips)
    protected TextView mTvTips;
    @BindView(R.id.CustomSelectionFragment_iv_left)
    protected ImageView mIvLeft;
    @BindView(R.id.CustomSelectionFragment_iv_right)
    protected ImageView mIvRight;
    @BindView(R.id.CustomSelectionFragment_iv_top)
    protected ImageView mIvTop;
    @BindView(R.id.CustomSelectionFragment_iv_bottom)
    protected ImageView mIvBottom;
    private List<SameSizeFrame> mData;
    private CustomSelectionVerticalFragmentFactory mFactory;
    private boolean mIsShowPerView = false;
    private ProgressDialogFragment mProgressDialogFragment;
    private MaterialLibraryTask mUpLoadTask;
    private String mMaterialId;
    private int mType;
    private int mContainerHeight;
    private double mScale;
    private BottomSheetDialog mDialogBuy;
    private boolean isStartShoppingCart = true;

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        setHasOptionsMenu(true);
    }

    public static CustomSelectionFragment newInstance(int type) {
        CustomSelectionFragment fragment = new CustomSelectionFragment();
        fragment.init(type);
        return fragment;
    }

    private void init(@Type int type) {
        this.mType = type;
        if (type == CUSTOM_MADE) {
            mData = CreateFrameData.makeFrameAllData();
        } else if (type == POSTER) {
            mData = CreateFrameData.makePosterAllData();
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_custom_selection_horizontal;
    }

    @Override
    protected void initView() {

        if (mData == null) {
            init(mType);
        }

        startArrowAnim();

        //初始化名称编辑框的光标
        mLlContainer.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
            @Override
            public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
                if (oldBottom == 0 || mContainerHeight == 0) {
                    return;
                }

                if (bottom == mContainerHeight) {
                    mEtName.setCursorVisible(false);
                    mEtName.setHint("未命名");
                }

                if (bottom < mContainerHeight && oldBottom == mContainerHeight) {
                    mEtName.setCursorVisible(true);
                    mEtName.setHint("");
                }
            }
        });
        mLlContainer.post(new Runnable() {
            @Override
            public void run() {
                mContainerHeight = mLlContainer.getHeight();
            }
        });


        final SelectionVerticalPagerAdapter mPagerAdapter = new SelectionVerticalPagerAdapter(
                getChildFragmentManager(), mData);
        mFactory = CustomSelectionVerticalFragmentFactory.getInstance();

        mViewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                FrameData frameData = mData.get(position).getData().get(0);
                setText(0, frameData.getShapeType(), null);

                if (mType == POSTER) {
                    setText(frameData.getPrice(), frameData.getShapeType(),
                            frameData.getShowSize());
                }

            }
        });
        mViewPager.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    UIUtils.hiddenKeyboard(getView());
                }
                setArrowVisibleGone();
                return false;
            }
        });

        mViewPager.post(new Runnable() {
            @Override
            public void run() {
                float height = mViewPager.getHeight();
                initHeightInChild(height);
                mViewPager.setAdapter(mPagerAdapter);
            }
        });

        mLlContainer.setOnClickListener(this);
        mBtnNext.setOnClickListener(this);
        mViewPager.setOnClickListener(this);

        FrameData frameData = mData.get(0).getData().get(0);
        setText(frameData.getPrice(), frameData.getShapeType(), frameData.getShowSize());

        mProgressDialogFragment = ProgressDialogFragment.newInstance("上传图片中，请稍等");
        mProgressDialogFragment.setOnBackPressListener(new Action0() {
            @Override
            public void call() {
                if (mUpLoadTask != null) {
                    mUpLoadTask.cancel();
                }
            }
        });
    }

    private void setArrowVisibleGone() {
        mIvBottom.setVisibility(View.GONE);
        mIvLeft.setVisibility(View.GONE);
        mIvRight.setVisibility(View.GONE);
        mIvTop.setVisibility(View.GONE);
    }

    private void startArrowAnim() {
        if (mType == POSTER) {
            mIvTop.setVisibility(View.GONE);
            mIvBottom.setVisibility(View.GONE);
        }

        startScaleAnimTogether(mIvLeft, mIvTop, mIvRight, mIvBottom);
    }


    private void startScaleAnimTogether(View... targets) {
        for (View target : targets) {
            startScaleAnim(target);
        }
    }

    private void startScaleAnim(View target) {
        ObjectAnimator scaleX = ObjectAnimator.ofFloat(target, View.SCALE_X, 0.75f, 1.9f);
        scaleX.setRepeatMode(ValueAnimator.REVERSE);
        scaleX.setRepeatCount(10000);
        ObjectAnimator scaleY = ObjectAnimator.ofFloat(target, View.SCALE_Y, 0.75f, 1.9f);
        scaleY.setRepeatMode(ValueAnimator.REVERSE);
        scaleY.setRepeatCount(10000);

        AnimatorSet set = new AnimatorSet();
        set.playTogether(scaleX, scaleY);
        set.setDuration(500);
        set.start();
    }



    private void initHeightInChild(float height) {
        for (SameSizeFrame data : mData) {
            data.setHeight(height);
        }
    }

    public void setText(int price, String content, String size) {
        mTvContent.setText(content);
        if (price != 0) {
            mTvPrice.setText("￥" + String.valueOf(price));
        }
        if (!TextUtils.isEmpty(size)) {
            if (!size.contains("mm")) {
                size += " mm";
            }
            mTvSize.setText(size);
        }
    }

    public void updateChildImageViewContent(String id, String path, double scale) {
        this.mMaterialId = id;
        this.mScale = scale;
        List<CustomSelectionVerticalFragment> fragments = mFactory.getFragments();
        for (CustomSelectionVerticalFragment fragment : fragments) {
            fragment.updateChildImageViewContent(path);
        }

        for (SameSizeFrame sameSizeFrame : mData) {
            for (FrameData data : sameSizeFrame.getData()) {
                data.getImage().setContentImage(path);
            }
        }
        mIsShowPerView = true;
        getActivity().invalidateOptionsMenu();
    }

    @Override
    public void onPrepareOptionsMenu(Menu menu) {
        menu.findItem(R.id.menu_preview).setVisible(mIsShowPerView);
        super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_preview:
                FrameData frameData = getCurrentFrameData();
                String name = mEtName.getText().toString();
                if (TextUtils.isEmpty(name)) {
                    name = "未命名";
                }
                frameData.setTitle(name);
                ImageData image = frameData.getImage();
                SuitableSizeHelper.getHelper().setFrameData(frameData);

                PreviewActivity.start(mContext, image.getFrameNot9ResourceId(), image.getContentImage(),
                        frameData.getWidth(), frameData.getHeight(), mType, mMaterialId);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    public void updateTips(boolean isUpdateTips) {
        mTvTips.setVisibility(isUpdateTips ? View.VISIBLE : View.INVISIBLE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.CustomSelectionFragment_btn_next:
                final FrameData frameData = getCurrentFrameData();
                String contentImage = frameData.getImage().getContentImage();
                if (TextUtils.isEmpty(contentImage)) {
                    ToastUtil.show("请选择图片");
                } else {
                    String name = mEtName.getText().toString();
                    if (TextUtils.isEmpty(name)) {
                        name = "未命名";
                    } else if (name.length() > 10) {
                        ToastUtil.show("请修改名称在10字以内");
                        return;
                    }
                    frameData.setTitle(name);
                    SuitableSizeHelper.getHelper().setFrameData(frameData);
                    uploadImage(frameData, contentImage);
                }
                break;
            case R.id.CustomSelectionFragment_ll_container:
                UIUtils.hiddenKeyboard(getView());
                break;
            case R.id.ItemBottomAddVideo_tv_add_shopping_cart:
                addShoppingCart();
                break;
            case R.id.ItemBottomAddVideo_tv_buy:
                GeneralActivity.start(mContext, GeneralActivity.ORDER, "确认订单");
                break;
            case R.id.ItemBottomAddVideo_tv_cancel:
                mDialogBuy.dismiss();
                break;
        }
    }

    private void uploadImage(final FrameData frameData, String contentImage) {
        mUpLoadTask = new MaterialLibraryTask();
        User user = AppProfile.getUserInfo().getUser();
        mProgressDialogFragment.show(getChildFragmentManager(), mProgressDialogFragment.getOurTag());

        // 选择素材库的图片
        if (contentImage.contains("http:") && !TextUtils.isEmpty(mMaterialId)) {
            buildDataAndStartNextActivity(mMaterialId, frameData, true);
            return;
        }

        mUpLoadTask.uploadMaterial(user.getPassId(), NetConstant.CLIENT_CODE,
                contentImage, new Action1<UploadMaterialData>() {
                    @Override
                    public void call(UploadMaterialData data) {
                        if (mUpLoadTask.isCancel()) {
                            return;
                        }

                        buildDataAndStartNextActivity(data.getId(), frameData, false);
                    }
                });
    }

    private void buildDataAndStartNextActivity(String id, FrameData frameData, boolean isFromNetMaterial) {
        SuitableSizeHelper helper = SuitableSizeHelper.getHelper();
        Works works = helper.getWorks();
        Works.MaterialEditBean bean = works.getEditBean(0);
        if (bean == null) {
            bean = works.addEditBean(new Works.MaterialEditBean())
                    .getEditBean(0);
        }
        bean.setMaterialId(id);

        if (isFromNetMaterial) {
            bean.setScale((float) mScale);
        }

        String typeCode;
        if (mType == POSTER) {
            typeCode = "haibao";
        } else {
            typeCode = "kuanghua";
        }
        works.setWorksName(frameData.getTitle())
                .setWorksPrice(frameData.getPrice())
                .setWorksTypeCode(typeCode)
                .setWorksShape(frameData.getShapeType())
                .setWorksColor("")
                .setWorksSize(frameData.getSize())
                .setWorksQuantity(1)
                .setSkuCode(frameData.getSku())
                .setMaterialId(id)
                .setWorksClientCode("android")
                .setWorksChannelCode("artron");
        mProgressDialogFragment.dismiss();

//        GeneralActivity.start(mContext, GeneralActivity.ADD_VIDEO, "添加视频");
        //TODO 以后需要删除的逻辑
        //购买相关的底部弹框
        mDialogBuy = new BottomSheetDialog(mContext);
        mDialogBuy.setContentView(R.layout.layout_bottom_add_shopping_cart_or_buy);

        View btnShoppingCart = mDialogBuy.findViewById(R.id.ItemBottomAddVideo_tv_add_shopping_cart);
        if (btnShoppingCart != null) {
            throttleFirst(btnShoppingCart, this);
        }

        View btnBuy = mDialogBuy.findViewById(R.id.ItemBottomAddVideo_tv_buy);
        if (btnBuy != null) {
            throttleFirst(btnBuy, this);
        }

        View btnCancel = mDialogBuy.findViewById(R.id.ItemBottomAddVideo_tv_cancel);
        if (btnCancel != null) {
            btnCancel.setOnClickListener(this);
        }

        mDialogBuy.getDelegate().findViewById(android.support.design.R.id.design_bottom_sheet)
                .setBackgroundResource(android.R.color.transparent);
        mDialogBuy.show();
    }

    private void addShoppingCart() {
        final ProgressDialogFragment fragment = ProgressDialogFragment.newInstance("正在加入购物车");
        fragment.show(getChildFragmentManager(), fragment.getOurTag());
        fragment.setOnBackPressListener(new Action0() {
            @Override
            public void call() {
                isStartShoppingCart = false;
            }
        });

        SuitableSizeHelper helper = SuitableSizeHelper.getHelper();
        Works works = helper.getWorks();
        Observable<Response> api = AddShoppingCartTask.addShoppingCart(works);
        RetrofitHelper.subscript(api, new Action1<Response>() {
            @Override
            public void call(Response response) {
                Log.d(TAG, "call: " + response);
                fragment.dismiss();
                if (isStartShoppingCart) {
                    HomeFragmentFactory.getInstance().updateShoppingCart();
                    GeneralActivity.start(mContext, GeneralActivity.SHOPPING_CART,
                            "购物车");
                }

            }
        });
    }

    private FrameData getCurrentFrameData() {
        int horizontalPosition = mViewPager.getCurrentItem();
        CustomSelectionVerticalFragment fragment = mFactory.getFragment(horizontalPosition);
        int verticalPosition = fragment.getVerticalViewPager().getCurrentItem();
        SameSizeFrame sameSizeFrame = mData.get(horizontalPosition);
        return sameSizeFrame.getData().get(verticalPosition);
    }

    @Override
    public void onDestroy() {
        if (mFactory != null) {
            mFactory.destroy();
        }
        super.onDestroy();

    }
}
